from flask import Blueprint, jsonify, request
from app.models.question import Question
from app.models.score import Score
from app.models.user import User
from app.utils import JwtToken
from app.extensions import db


import random

question_bp = Blueprint('question_bp', __name__)

dic = {
    "A": 0,
    "B": 1,
    "C": 2,
    "D": 3,
}

@question_bp.route('/api/get-question', methods=['GET'])
def get_question():
    try:
        all_questions = Question.query.all()
        selected = random.sample(all_questions, min(10, len(all_questions)))

        data = [
            {
                "type": 0,
                "title": q.name + "是什么垃圾？",
                "answer": dic[q.answer],
                "id": 0
            }
            for q in selected
        ]

        return jsonify({
            'code': 200,
            'msg': 'success',
            'data': data
        })
    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500


@question_bp.route('/api/submit', methods=['POST'])
def submit():
    # 1. 从请求头里拿 Bearer Token
    auth_header = request.headers.get("Authorization", None)
    # print(request)

    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

    token = auth_header.split(" ")[1]

    # 2. 解析 token 获取 openid
    payload, verify_status = JwtToken.parse_token(token)
    if not verify_status or "openid" not in payload:
        return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

    openid = payload["openid"]

    # 3. 获取参数（用户得分）
    data = request.get_json()
    score = data.get("score")

    if score is None:
        return jsonify({'code': 400, 'msg': '缺少 score 参数'}), 400

    # 4. 查询用户
    user = User.get_user_by_openid(openid)
    if not user:
        return jsonify({'code': 404, 'msg': '用户不存在'}), 404

    # 5. 保存分数
    new_score = Score(openid=user.openid, score=score)
    db.session.add(new_score)
    db.session.commit()

    return jsonify({
        'code': 200,
        'msg': 'success',
    })
